package com.zsummer.zero.jdk.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
	
	public static void main(String[] args) {
		while (true) {
			server();
		}
	}

	private static void server() {
		// 监听指定端口
		int port = 55533;
		ServerSocket server = null;
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;
		try {
			server = new ServerSocket(port);
			System.out.println("等待链接");
			socket = server.accept();
			// 从socket获取输入流，建立缓冲区读取信息
			is = socket.getInputStream();
			byte[] bytes = new byte[1024];
			int len = 0;
			StringBuilder sb = new StringBuilder();
			while((len = is.read(bytes)) != -1) {
				sb.append(new String(bytes, 0, len, "UTF-8"));
			}
			System.out.println(sb.toString());
			
			// 从socket获取输出流， 写入信息
			os = socket.getOutputStream();
			os.write("sweat i wash clean already".getBytes("UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (server != null) {
					server.close();
				}
				if (socket != null) {
					socket.close();
				}
				if (is != null) {
					is.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
